<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


            <el-form-item label="报修区域" prop="name" >
             <el-select v-model="queryParams.areaId" placeholder="请选择报修区域"
            clearable
              @keyup.enter.native="handleQuery">
                <el-option
                  v-for="item in areaOptions"
                  :key="item.areaId"
                  :label="item.name"
                  :value="item.areaId"
                ></el-option>
              </el-select>
          </el-form-item>

      <el-form-item label="详细位置" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入故障详细位置"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>



      <el-form-item label="紧急程度" prop="urgency">
  <el-select
    v-model="queryParams.urgency"
    placeholder="请选择紧急程度"
    clearable
    @change="handleQuery"
  >
    <el-option label="低" value="0"></el-option>
    <el-option label="一般" value="1"></el-option>
    <el-option label="紧急" value="2"></el-option>
  </el-select>
</el-form-item>

      <el-form-item label="报修状态" prop="status">
  <el-select
    v-model="queryParams.status"
    placeholder="请选择报修状态"
    clearable
    @change="handleQuery"
  >
    <el-option label="未提交" value="7"></el-option>
    <el-option label="打回修改" value="1"></el-option>
    <el-option label="待处理" value="2"></el-option>
    <el-option label="正在维修" value="3"></el-option>
    <el-option label="已完成" value="4"></el-option>
    <el-option label="退单中" value="5"></el-option>
    <el-option label="转单中" value="6"></el-option>
  </el-select>
</el-form-item>


      <el-form-item label="创建时间" prop="createdAt" >
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="更新时间" prop="updatedAt" >
        <el-date-picker clearable
          v-model="queryParams.updatedAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="实例id" prop="flowInstantId" v-show="false">
        <el-input
          v-model="queryParams.flowInstantId"
          placeholder="请输入实例id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ycl:request:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ycl:request:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ycl:request:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ycl:request:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain

          size="mini"
          @click="zhu"
          v-hasPermi="['ycl:request:add']"
        >饼图</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="requestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报修ID" align="center" prop="requestId" />
      <el-table-column label="用户ID" align="center" prop="userId" />

      <el-table-column label="用户名称" align="center" prop="userName" />

      <el-table-column label="报修区域" align="center" prop="areaName" />

      <el-table-column label="故障描述" align="center" prop="description" width="200"/>
      <el-table-column label="故障详细位置" align="center" prop="location" />
      <el-table-column label="设备类型" align="center" prop="mname" />

      <el-table-column prop="urgency" label="紧急程度" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.request_type" :value="scope.row.urgency"/>
        </template>
      </el-table-column>

      <el-table-column label="图片" align="center">
        <template slot-scope="scope">
          <img
            v-if="scope.row.picture"
            :src="scope.row.picture"
            alt="图片预览"
            style="width: 50px; height: 50px; cursor: pointer; border: 2px solid transparent; transition: border-color 0.3s;"
            @click="showLargeImage(scope.row.picture)"
            @mouseover="hoverImage(true)"
            @mouseout="hoverImage(false)"
          />
        </template>
      </el-table-column>

      <el-table-column prop="status" label="报修状态" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.request_status" :value="scope.row.status"/>
        </template>
      </el-table-column>

            <el-table-column label="维修人员" align="center" prop="name" />

<el-table-column label="创建时间" align="center" prop="createdAt" width="180">
  <template slot-scope="scope">
    <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
  </template>
</el-table-column>

      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
           <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ycl:request:edit']"
            v-show="scope.row.status==7"
          >修改</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ycl:request:edit']"
            v-show="scope.row.status==1"
          >打回修改</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ycl:request:remove']"
                        v-show="scope.row.status==7"
          >删除</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-single"
            @click="handleRequestSubmit(scope.row.requestId)"
            v-hasPermi="['ycl:request:resuestSubmit']"
            v-show="scope.row.status==7||scope.row.status==1"
          >提交报修申请</el-button>

          <el-col :span="1.5" style="display: flex; justify-content: center; align-items: center;">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="ping"
              v-hasPermi="['ycl:request:add']"
              v-show="scope.row.status == 4"
            >
              去评价
            </el-button>
          </el-col>

          <el-col :span="1.5" style="display: flex; justify-content: center; align-items: center;">
            <el-button
              type="success"
              plain
              size="mini"
              
              v-hasPermi="['ycl:request:add']"
              v-show="scope.row.status == 8"
            >
              已评价
            </el-button>
          </el-col>


          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownImage(scope.row.picture)"
            v-hasPermi="['ycl:RepairRequest:down']"
          >下载</el-button>



        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报修请求对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

       <el-form-item label="报修区域">
             <el-select v-model="form.areaId" placeholder="请选择报修区域">
                <el-option
                  v-for="item in areaOptions"
                  :key="item.areaId"
                  :label="item.name"
                  :value="item.areaId"
                ></el-option>
              </el-select>
        </el-form-item>

        <el-form-item label="故障描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="详细位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入故障详细位置" />
        </el-form-item>

        <el-form-item label="设备类型">
             <el-select v-model="form.materialId" placeholder="请选择设备类型">
                <el-option
                  v-for="item in materialOptions"
                  :key="item.materialId"
                  :label="item.name"
                  :value="item.materialId"
                ></el-option>
              </el-select>
        </el-form-item>

            <el-form-item label="紧急程度">
              <el-radio-group v-model="form.urgency">
                <el-radio
                  v-for="dict in dict.type.request_type"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>



        <el-form-item label="图片" prop="picture" v-show="false">
          <el-input v-model="form.picture" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-image
         style="width: 300px; height: 300px"
          :src="url"
          :fit="fit" ref="imageId" >
        </el-image>

      <el-upload
        ref="uploadFile"
        :limit="1"
        accept=".bmp,.jpg,.jpeg,.png,gif"
        :headers="uploadData.headers"
        :action="uploadData.url"
        :disabled="uploadData.isUploading"
        :on-progress="handleFileUploadDataProgress"
        :on-success="handleFileDataSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <span>仅允许导入bmp、jpg、jpeg、gif、png格式文件。</span>
      </el-upload>

       <el-button type="primary" @click="submitFileFormImage">上传图片</el-button>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 显示大图的模态框 -->
    <el-dialog :visible.sync="dialogVisible" width="50%">
      <img :src="largeImageUrl" alt="大图预览" style="width: 100%;">
    </el-dialog>

  </div>
</template>

<script>
import {submitRepairRequest, listRequest, getRequest, delRequest, addRequest, updateRequest } from "@/api/ycl/request";
import { getAllAreas } from "@/api/ycl/area";
import { getToken } from "@/utils/auth";
import {getAllMaterials} from "@/api/ycl/material";

export default {
  name: "Request",
  dicts: ["request_type","request_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      //报修区域名称
      areaOptions: [],
      materialOptions:[],

      // 报修请求表格数据
      requestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 图片导入参数
      uploadData: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ycl/request/uploadMinio"
      },


      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        areaId: null,
        description: null,
        location: null,
        materialId: null,
        urgency: null,
        status: null,
        createdAt: null,
        updatedAt: null,
        flowInstantId: null,
        picture: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

      url: '', // 初始图片URL
      fit: 'contain', // 图片适应方式，这里设置为'contain'

      dialogVisible: false,
      largeImageUrl: '',
      borderColor: 'transparent'
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询报修请求列表 */
    getList() {
      this.loading = true;
      listRequest(this.queryParams).then(response => {
        this.requestList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.requestList);
        this.form.picture=this.url;

      });

      getAllAreas().then(
        response=>{

          this.areaOptions=response.data;
        }
      );

      getAllMaterials().then(
        response=>{

          this.materialOptions=response.data;
        }
      );

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        requestId: null,
        userId: null,
        areaId: null,
        description: null,
        location: null,
        materialId: null,
        urgency: null,
        status: null,
        createdAt: null,
        updatedAt: null,
        flowInstantId: null,
        picture: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      console.log(this.queryParams);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.requestId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报修请求";

      getAllAreas().then(
        response=>{
          console.log(response.data);
          this.areaOptions=response.data;
        }
      );

      getAllMaterials().then(
        response=>{
          console.log(response.data);
          this.materialOptions=response.data;
        }
      );

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const requestId = row.requestId || this.ids
      getRequest(requestId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改报修请求";

        this.url=this.form.picture;

      });

      getAllAreas().then(
        response=>{
          console.log(response.data);
          this.areaOptions=response.data;
        }
      );

       getAllMaterials().then(
        response=>{
          console.log(response.data);
          this.materialOptions=response.data;
        }
      );

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.requestId != null) {
            updateRequest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRequest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const requestIds = row.requestId || this.ids;
      this.$modal.confirm('是否确认删除报修请求编号为"' + requestIds + '"的数据项？').then(function() {
        return delRequest(requestIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ycl/request/export', {
        ...this.queryParams
      }, `request_${new Date().getTime()}.xlsx`)
    },


    // 图片文件上传中处理
    handleFileUploadDataProgress(event, file, fileList) {
      console.log(getToken());
      console.log(event);
      console.log(file+"333");
      console.log(fileList+"333");
      this.upload.isUploading = true;
    },
    // 图片文件上传成功处理
    handleFileDataSuccess(response, file, fileList) {
       console.log(response);
       console.log(response.msg);
       console.log(file+"444");
       console.log(fileList+"555");
      this.uploadData.open = false;
      this.uploadData.isUploading = false;
      this.$refs.uploadFile.clearFiles();

      this.form.picture=response.msg;
      this.url=this.form.picture;

      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "上传图片成功！" + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    },
    // 提交上传文件
    submitFileFormImage() {
      this.$refs.uploadFile.submit();
    },

          //图片下载
    handleDownImage(filename){
     let pos=filename.lastIndexOf("/");
     filename=filename.substring(pos);
     let extendName=filename.substring(filename.indexOf("."))
     this.download('ycl/request/imageDown', {fileName:filename
      }, `student_image_${new Date().getTime()}`+extendName)

    },

  // 显示大图
  showLargeImage(url) {
    this.largeImageUrl = url;
    this.dialogVisible = true;
  },

  // 鼠标悬停效果
    hoverImage(isHovering) {
      this.borderColor = isHovering ? '#409EFF' : 'transparent';
    },

    //提交报修申请
    handleRequestSubmit(requestId){
        submitRepairRequest(requestId).then(response => {
          console.log(response)
          this.getList();
          this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "提交申请成功！" + "</div>", "提示框", { dangerouslyUseHTMLString: true });
       });
   },
    zhu(){
      this.$router.push({ name: 'zhu' })
    },
    ping(){
      this.$router.push({ name: 'ping' })
    }




  }
};
</script>
